layui.define(['exbase', 'jquery', 'ExForm', 'layer'], function (exports) {
    var $ = layui.$;
    var exbase = layui.exbase;

    function DynamicForm(data) {
        var _this = this;
        this.hideButtons = data.hideButtons;
        this.elem = data.elem;
        this.title = data.title;
        this.form = data.form;
        this.url = data.url;
        this.method = data.method || "GET";
        this.contentType = data.contentType || "application/x-www-form-urlencoded";
        this.success = data.success;
        this.form_id = data.form_id || exbase.generateId("dynamic_form");
        this.data = data.data;
        this.onload = data.onload;

        this.selectTreeConfigs = {}

        this.loadFormData = function () {
            var url = _this.onload.url;
            var method = _this.onload.method;
            var data = _this.onload.data;
            var contentType = _this.contentType;

            if (contentType == "application/json") {
                data = JSON.stringify(data);
            }
            $.ajax({
                async: false,
                url: url,
                type: method,
                contentType: contentType,
                data: data,
                dataType: 'json',
                success: function (data) {
                    if (data.errorCode == exbase.AJAX_SUCCESS_CODE) {
                        _this.data = exbase.getJsonAsForm(data.data);
                    } else {
                        layer.msg("无法加载表单数据！<br>" + data.errorMsg, {icon: 2});
                    }
                }
            })
        }

        this.define = function () {
            if (_this.onload) {
                _this.loadFormData()
            }

            var html;
            layui.use('jquery', function () {
                var $ = layui.jquery;
                html = [`<form class='layui-form' id='${_this.form_id}' lay-filter='${_this.form_id}' style='margin-right:30px;margin-top:20px'>`,
                    function () {
                        if (_this.form) {
                            var array = new Array();
                            if (_this.title) {
                                array.push("<div class='layui-form-item'>")
                                array.push("<div class='layui-input-block'>")
                                array.push(`<h2>${_this.title}</h2>`)
                                array.push("</div></div>")
                            }

                            _this.form.forEach(function (e) {
                                if (e.type == 'hide') {
                                    array.push("<div class='layui-form-item  layui-hide'>");
                                } else {
                                    array.push("<div class='layui-form-item'>");
                                }
                                var value = e.value
                                if (_this.data) {
                                    value = _this.data[e.name]
                                }
                                if (e.type == 'select-tree') {
                                    _this.selectTreeConfigs[e.name] = e.config
                                }

                                array.push(`<label class='layui-form-label'>${e.label}</label>`);
                                array.push("<div class='layui-input-block'>");
                                if (e.type == 'text' || e.type == 'password' || e.type == 'hide') {
                                    array.push(`<input type='${e.type}' name='${e.name}' value='${value || ""}' ${e.required? 'required' : ''} lay-verify='${e.verify}' placeholder='${e.placeholder || ""}' autocomplete='off' class='layui-input'>`);
                                } else if(e.type == 'select-tree') {
                                    array.push(`<input type='text' name='${e.name}' value='${value || ""}' ${e.required? 'required' : ''} lay-verify='${e.verify}' placeholder='${e.placeholder || ""}' autocomplete='off' class='layui-input select-tree-tag'>`);
                                } else if (e.type == 'select') {
                                    array.push(` <select name="${e.name}" lay-verify='${e.verify}' ${e.multiple? 'multiple' : ''} ${e.dict_url? 'dict-url=\"' + e.dict_url + "\"": ''}>`)
                                    e.options && e.options.forEach(function (e1) {
                                        var selected = ""
                                        if (e1.selected || e1.value == value) {
                                            selected = "selected"
                                        }

                                        array.push(`<option value="${e1.value}" ${selected}>${e1.label}</option>`)
                                    })
                                    array.push(` </select>`)
                                } else if (e.type == 'radio') {
                                    e.options && e.options.forEach(function (e1) {
                                        var checked = "";
                                        if (e1.checked || e1.checked === "checked" || e1.value == value) {
                                            checked = "checked"
                                        }
                                        array.push(`<input type="radio" name="${e.name}" value="${e1.value}" title="${e1.label}" lay-verify='${e1.verify}' ${checked}>`)
                                    })
                                    if (!e.options) {
                                        var checked = "";
                                        if (e.checked || e.checked === "checked" || e.value == value) {
                                            checked = "checked"
                                        }
                                        array.push(`<input type="radio" name="${e.name}" value="${e.value}" lay-verify='${e.verify}' ${checked} lay-skin="switch" lay-text="开启|关闭"> `)
                                    }
                                } else if (e.type == 'checkbox') {
                                    e.options && e.options.forEach(function (e1) {
                                        var checked = "";
                                        if (e1.checked || e1.checked === "checked" || e1.value == value) {
                                            checked = "checked"
                                        }
                                        array.push(`<input type="checkbox" name="${e.name}" title="${e1.label}" value="${e1.value}" lay-verify='${e1.verify}' ${checked}>`)
                                    })
                                    if (!e.options) {
                                        var checked = "";
                                        if (e.checked || e.checked === "checked" || e.value == value) {
                                            checked = "checked"
                                        }
                                        array.push(`<input type="checkbox" name="${e.name}" value="${e.value}" lay-verify='${e.verify}' ${checked} lay-skin="switch" lay-text="开启|关闭"> `)
                                    }
                                } else if (e.type == 'textarea') {
                                    array.push(`<textarea name="${e.name}" placeholder='${e.placeholder || ""}' value='${value || ""}' lay-verify='${e.verify}' class="layui-textarea"></textarea>`)
                                }
                                array.push("</div>");
                                array.push("</div>");
                            })
                            return array.join("");
                        }
                    }(),
                    function () {
                        if (_this.url) {
                            return ["<div class='layui-form-item " + (_this.hideButtons ? 'layui-hide':'') + "'>",
                                "<div class='layui-input-block'>",
                                `<button class="layui-btn" lay-submit id="submit_${_this.form_id}" lay-filter="submit_${_this.form_id}">提交</button>`,
                                `<button type="reset" class="layui-btn layui-btn-primary">重置</button>`,
                                "</div>",
                                "</div>"
                            ].join("");
                        }
                    }(),
                    "</form>"].join("");
            });
            return html;
        };

        this.render = function () {
            _this.renderInternal()
        }

        this.renderInternal = function () {
            var html = _this.define();
            $(_this.elem).html(html);
            layui.ExForm.render(null, _this.form_id, _this.selectTreeConfigs);

            layui.form.on('submit(submit_' + _this.form_id +')', function(data){
                var $form = $("#" + _this.form_id);
                var submit_data = data.field;
                if (_this.contentType == "application/json") {
                    var tmp = exbase.getFormAsJson($form);
                    submit_data = JSON.stringify(tmp);
                }
                var loadingIndex = layer.load(1, {
                    shade: [0.1] //0.1透明度的白色背景
                });
                $.ajax({
                    url: _this.url,
                    type: _this.method,
                    contentType: _this.contentType,
                    data: submit_data,
                    dataType: 'json',
                    success: function (data) {
                        layer.close(loadingIndex);
                        if (data.errorCode == exbase.AJAX_SUCCESS_CODE) {
                            layer.msg("执行成功！", {icon: 1});
                            if (_this.success) {
                                _this.success(data);
                            }
                        } else {
                            layer.msg('失败：' + data.errorMsg, {icon: 2});
                        }
                    }
                });
                return false;
            });
        };

    }

    exports('DynamicForm', DynamicForm)
})